package com.raymond.thread.manager.utils;

import com.raymond.thread.manager.BaseThread;
import com.raymond.thread.manager.circulation.BaseCirculationThread;
import com.raymond.thread.manager.scheduled.BaseScheduledThread;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

/**
 * 线程管理工具类
 *
 * @author :  raymond
 * @version :  V1.0
 * @date :  2020-12-11 15:46
 */
public class ManagerThreadUtil {
    private static final Map<String, BaseThread> baseThreadMap = new ConcurrentHashMap<>();

    private static final Map<String, ScheduledFuture<?>> scheduledThread = new ConcurrentHashMap<>();

    /**
     * 获取管理的所有线程
     * @return 所有线程
     */
    public static List<BaseThread> findBaseThread() {
        return new ArrayList<>(baseThreadMap.values());
    }

    /**
     * 通过线程名称获取线程
     * @return 线程
     */
    public static BaseThread getBaseThread(String threadName) {
        return baseThreadMap.get(threadName);
    }

    /**
     * 退出循环线程和定时线程
     * @param threadName 线程名称
     * @return true退出成功
     */
    public static boolean threadExit(String threadName) {
        BaseThread baseThread = baseThreadMap.get(threadName);
        if (BaseCirculationThread.class.isAssignableFrom(baseThread.getClass())) {
            BaseCirculationThread circulationThread = (BaseCirculationThread) baseThread;
            circulationThread.currentThreadExit();
            baseThreadMap.remove(threadName);
            return true;
        } else if (BaseScheduledThread.class.isAssignableFrom(baseThread.getClass())) {
            ScheduledFuture<?> scheduledFuture = scheduledThread.get(threadName);
            scheduledFuture.cancel(true);
            baseThreadMap.remove(threadName);
            scheduledThread.remove(threadName);
            return true;
        }
        return false;
    }

    /**
     * 添加线程信息
     * @param baseThread 线程
     */
    public static void putBaseThread(BaseThread baseThread) {
        baseThreadMap.put(baseThread.getName(), baseThread);
    }

    /**
     * 添加定时线程
     * @param threadName 线程名称
     * @param scheduledFuture 定时线程
     */
    public static void putScheduledThread(String threadName, ScheduledFuture<?> scheduledFuture) {
        scheduledThread.put(threadName, scheduledFuture);
    }

}
